package cc.taofoo.NewCoder;

import java.util.*;
import java.util.Map;
import java.util.List;
public class Solution {

    Map<Integer,LinkNode> nodeMap = new HashMap<>();
    List<Integer> list = new ArrayList<>();
    LinkNode head = new LinkNode();
    LinkNode tail = new LinkNode();
    int linkLength = 0;
    int maxLength = 0;


    class LinkNode{
        LinkNode pre;
        LinkNode next;
        public int value,key;
        public LinkNode(){}
        public LinkNode(int key,int value){this.key=key;this.value = value;}
    }

    public void set(int key ,int value){
        LinkNode node = nodeMap.getOrDefault(key,null);
        if(node == null){
            node = new LinkNode(key,value);
            fresh(node,false);
        }else {
            node.value = value;
            fresh(node,true);
        }
        nodeMap.put(key,node);
    }

    public int get(int key){
         int res = -1;
         if(nodeMap.containsKey(key)){
             LinkNode node = nodeMap.get(key);
             res = node.value;
             fresh(node,true);
         }
         return res;
    }


    public void fresh(LinkNode node , boolean exist){
        if(exist){
            removeNode(node);
            addNode(node);
        }else{
            addNode(node);
            if(linkLength > maxLength){
                nodeMap.remove(tail.pre.key);
                removeNode(tail.pre);
            }
        }
    }

    public void addNode(LinkNode node){
        node.pre = head;
        node.next = head.next;
        head.next = node;
        node.next.pre = node;
        linkLength++;
    }

    public void removeNode(LinkNode node){
        node.pre.next = node.next;
        node.next.pre = node.pre;
        linkLength --;
    }

     /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
        head.next = tail;
        tail.pre = head;
        maxLength = k;

        for(int[] operator : operators){
            switch(operator[0]){
                case 1:
                    set(operator[1],operator[2]);
                    break;
                case 2:
                    int res = get(operator[1]);
                    list.add(res);
                    break;
            }
        }
        int out[] = new int[list.size()];
        int idx = 0;
        for(int i :list){
            out[idx++] = i;
        }
        return out;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] a = solution.LRU(new int[][]{{1, 1, 1}, {1, 2, 2}, {1, 3, 2}, {2, 1}, {1, 4, 4}, {2, 3},{2,4}}, 1);
        for(int x:a){
            System.out.println(x);
        }
    }

}